package com.orion.config;

import cn.hutool.json.JSONUtil;
import com.orion.domain.Result;
import com.orion.enumeration.CommonCodeEnum;
import com.orion.enumeration.Oauth2ExceptionCodeEnum;
import com.orion.service.impl.AuthUserDetailService;
import com.orion.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

/**
 * @author Administrator
 * @date 2021/8/24
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private AuthUserDetailService authenUserService;

    @Autowired
    private CustomBasicAuthenticationFilter customBasicAuthenticationFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

//只拦截/myoauth/**
//        http.authorizeRequests()
//                .antMatchers("/myoauth/**").authenticated()
//                .and()
//                .httpBasic()
//                .and()
//                .formLogin().and()
//                .csrf().disable();

        http.addFilterBefore(customBasicAuthenticationFilter, BasicAuthenticationFilter.class);

        http.authorizeRequests()
                .antMatchers("/oauthClient/**").permitAll()
                .anyRequest().authenticated()
                .and()
                //授权码模式得加上httpBasic 不然报403,前后分离就用basic，不然用formLogin也开httpBasic在basic之前加filter
                /*
                设置好authentication认证好再SecurityContextHolder.getContext().setAuthentication(authResult);，不然触发
                .exceptionHandling().authenticationEntryPoint 产生 InsufficientAuthenticationException异常。说还没认证身份；

                要不就直接省功夫用basic认证，
                demoUri： http://kalos:123456789@127.0.0.1:8547/oauth/authorize?client_id=ncsf6sb4&response_type=code&scope=user_info&state=orion
                */
                .httpBasic()
                //密码错误返回在这里配置，用户名在自定义userDetail里配置
                .authenticationEntryPoint((request, response, authException) -> {
                    System.out.println("basic commence AuthenticationException：" + authException);
                    Result r = Oauth2ExceptionCodeEnum.UNAUTHORIZED_CLIENT.toResult();
                    ResponseUtil.jsonResp(response).getWriter().write(JSONUtil.toJsonStr(r));
                })
                //.and()
                //formLogin在优先
                //.formLogin()
                /*.failureHandler((request, response, com.orion.exception) -> {
                    System.out.println("formLogin - > authenticationEntryPoint :" + com.orion.exception);
                    Result result = new Result(com.orion.exception.getMessage(), -1);
                    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                    response.setCharacterEncoding(StandardCharsets.UTF_8.name());
                    response.getWriter().write(JSONUtil.toJsonStr(result));
                })*/
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> {
                    System.out.println("security config commence AuthenticationException:" + authException.getMessage());
                    Result r = CommonCodeEnum.COMMON_SERVER_ERROR.toResult();
                    ResponseUtil.jsonResp(response).getWriter().write(JSONUtil.toJsonStr(r));
                })
                .accessDeniedHandler((request, response, accessDeniedException) -> {
                    System.out.println("security config commence accessDeniedException:" + accessDeniedException.getMessage());
                    Result r = Oauth2ExceptionCodeEnum.ACCESS_DENIED.toResult();
                    ResponseUtil.jsonResp(response).getWriter().write(JSONUtil.toJsonStr(r));
                })
                .and().csrf().disable();

                /* session 设置为 IF_REQUIRED 有需要才生成 */
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(authenUserService)
                .passwordEncoder(passwordEncoder());

        auth.authenticationProvider(preAuthenticatedAuthenticationProvider());
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PreAuthenticatedAuthenticationProvider preAuthenticatedAuthenticationProvider(){
        PreAuthenticatedAuthenticationProvider provider = new PreAuthenticatedAuthenticationProvider();
        provider.setPreAuthenticatedUserDetailsService(new UserDetailsByNameServiceWrapper<>(authenUserService));
        return provider;
    }
}
